<?php

/** 
 * 充值卡管理
 * @property Rechargecard_mdl $rechargecard
 * @property Search_tpl $searchTpl
 */
class Rechargecard extends \Admin_Controller {
	
	/**
	 */
	public function __construct() {
		parent::__construct ();
		$this->load->model('Rechargecard_mdl','rechargecard');
		$this->apiOutput->debug = TRUE;
	}
	
	public function index(){
		$this->load->library('Search_tpl',NULL,'searchTpl');
		$where = array();
		$like = array();
		$order = 'id';
		$sort  = 'DESC';
		$input = $this->input->get(NULL,TRUE);
		foreach ($input as $k=>$v){
			if ($v===''){
				continue;
			}
			$v = trim($v);
			switch ($k) {
				case 'rechargecardState':
					$v=(int)$v;
					if( $v===0 ){//未使用
						$where['userID']=0;
					}else if($v===1){//已用
						$where['userID >']=0;
					}
					break;
				case 'adminID':
					$where['adminID'] = (int)$v;
					break;
				case 'userID':
					$where['userID'] = (int)$v;
					break;
				case 'amount':
					$where['amount'] = (int)$v;
					break;
				case 'id':
					$where['id'] = $v;
					break;
				case 'flag':
					$where['flag'] = $v;
					break;
				case 'order' :
// 					$order = isset($orders[$v]) ? $orders[$v] : 'id';
					break;
				case 'sort':
					$sort = (int)$v===0 ? 'DESC' : 'ASC';
					break;
				case 'ct_st':
					$where['createTime >='] = strtotime($v);
					break;
				case 'ct_et':
					$where['createTime <='] = strtotime($v);
					break;
				case 'use_st':
					$where['useTime >='] = strtotime($v);
					break;
				case 'use_et':
					$where['useTime <='] = strtotime($v);
					break;
			}
		}
		
		$query = array();
		$query['select']= '*';
		$query['from']  = 'hs_rechargecard';
		$query['where'] = $where;
		$query['like']  = $like;
		$query['order'] = $order;
		$query['sort']  = $sort;
		$this->searchTpl->query($query);
		$temp = array();
		$temp['formItems'] = array(
				'rechargecardState',
				array('type'=>'text','label'=>'卡号','name'=>'id'),
				array('type'=>'text','label'=>'面值','name'=>'amount'),
				array('type'=>'text','label'=>'批次','name'=>'flag'),
				'br',  
				array('type'=>'text','label'=>'管理员ID','name'=>'adminID'),
				array('type'=>'text','label'=>'使用者ID','name'=>'userID'),
				'br',
				array('type'=>'dateRange','label'=>'生成时间','name'=>array('ct_st','ct_et')),
				array('type'=>'dateRange','label'=>'使用时间','name'=>array('use_st','use_et')),
		);
		$temp ['thList'] = array (
				'卡号','生成时间','面值(元)','管理员ID','管理员','批次','使用者','使用者ID','使用时间',
		);
		
		
		// 		pr($schoolList);die;
		$admins = $this->admin->getAdminList();
		$callback = function($v)use($admins){
			return array(
					$v['id'],
					date('Y-m-d H:i:s',$v['createTime']),
					(int)$v['amount']/100,
					$v['adminID'],
					empty($admins[$v['adminID']]) ? '' : $admins[$v['adminID']]['username'],
					$v['flag'],
					'',
					$v['userID'],
					empty($v['useTime']) ? '' : date('Y-m-d H:i:s',$v['useTime']),
			);
		};
		$temp['tableTitle'] = '用户列表--共查到%s个充值卡--';
		$temp['header'] = $this->getViewHeaderData();
// 		$temp['jsCtrl'] = 'userCtrl';
		$this->searchTpl->show($temp,$callback);
	}
	
	
	
	public function generate(){
		if( empty($_REQUEST['download']) ){
			$this->showView('admin/rechargecard/generate');
		}else{
			$this->_generate();
		}
	}
	
	
	
	
	/**
	 * 批量生成充值卡
	 */
	public function _generate(){
		$amount = (int)$this->input->post_get('amount');
		$count  = (int)$this->input->post_get('count');
		$admin = $this->admin->getUser() ;
		
		$adminId = $admin['id'];
		$amount = $amount*100;
		// 批量生成卡并获取批次号
		$flag = $this->rechargecard->generateCard($count,$amount,$adminId);
		// 下载该批卡信息
		$where  = array('flag'=>$flag);
		$this->_download($where,$flag);
	}
	
	protected function _download($where,$filename){
		$select = 'id,cardpwd,amount,createTime,flag';
		$list = $this->rechargecard->getList ( $select, $where );
		array_walk ( $list, function (&$card) {
			$card['cardpwd'] = (string)$card['cardpwd']."\t";
			$card ['amount'] = ( int ) ($card ['amount'] / 100);
			$card ['createTime'] = date ( 'Y-m-d H:i:s', $card ['createTime'] );
		} );
		// CSV下载 
		$CSV = new CSVFile ();
		$CSV->setTitle ( '卡号', '密码', '金额(元)', '生成时间','批次号' )
			->setData ( $list )
			->toCSV ()
			->download ( $filename );
	}
}

class CSVFile{
	protected $titles=array();
	protected $filename='';
	protected $list = array();
	protected $csvStr='';
	
	
	public function setTitle(){
		$this->titles = func_get_args();
		return $this;
	}
	public function setFilename($filename){
		$this->filename = $filename;
		return $this;
	}
	public function setData($list){
		$this->list = $list;
		return $this;
	}
	
	public function toCSV(){
		if( ! empty($this->titles) ){
			$this->appendRow($this->titles);
		}
		
		foreach ($this->list as $row){
			$this->appendRow($row);
		}
		return $this;
	}
	
	protected function appendRow($data){
		$data = implode(',', $data);
		$data = iconv('UTF-8', 'GB2312', $data);
		$this->csvStr.=$data."\r\n";
	}
	
	protected function getFilename(){
	}
	
	public function download($filename){
		header("Content-type:text/csv");
		header("Content-Disposition:attachment;filename={$filename}.csv");
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		echo $this->csvStr;
	}
	
	
}












